<template>
<!-- 针对性训练题部分 -->
<div class="training-section">
  <header class="training-header">
    <div class="header-content">
      <h1><i class="fas fa-microphone-alt"></i> 针对性训练题</h1>
      <p class="subtitle">提供专业化的题目训练，获得专业评测反馈，快速提升专业水平</p>
    </div>
  </header>
  <!-- <h2 class="section-title"><i class="el-icon-edit-outline"></i> 针对性训练题</h2> -->
  <el-card shadow="hover" class="training-card">
    <!-- <div class="training-header"> -->
      <!-- <h3>基于知识薄弱点的专项训练</h3> -->
      <!-- <el-tag type="warning">共 {{ trainingQuestions.length }} 道题</el-tag> -->
    <!-- </div> -->
    <div v-if="trainingQuestions.length > 0" class="questions-container">
      <div 
        v-for="(question, index) in trainingQuestions" 
        :key="index" 
        class="question-item"
        :class="{ 'active-question': activeQuestionIndex === index }"
      >
        <div class="question-header">
          <div class="question-number">题目 {{ index + 1 }}</div>
          <div class="question-type">
            <el-tag :type="question.type === '简答题' ? 'success' : 'primary'">
              {{ question.type }}
            </el-tag>
          </div>
        </div>
        <div class="question-content">
          <p>{{ question.question }}</p>
          <!-- 选择题选项 -->
          <div v-if="question.type === '选择题'" class="options-container">
            <div 
              v-for="(option, optIndex) in question.options" 
              :key="optIndex" 
              class="option-item"
              :class="{ 'selected': userAnswers[index] === option }"
              @click="selectOption(index, option)"
            >
              <!-- <span class="option-letter">{{ String.fromCharCode(65 + optIndex) }}.</span> -->
              <span class="option-text">{{ option }}</span>
            </div>
          </div>
        </div>
        <!-- 用户作答区域 -->
        <div v-if="question.type === '简答题'" class="answer-input">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请在此输入您的回答..."
            v-model="userAnswers[index]"
            resize="none"
          ></el-input>
        </div>
        <!-- 操作按钮 -->
        <div class="question-actions">
          <el-button 
            type="primary" 
            @click="showAnswer(index)"
            :disabled="userAnswers[index] === ''"
          >
            <i class="el-icon-view"></i> 查看参考答案
          </el-button>
          <el-button 
            type="text" 
            @click="toggleQuestion(index)"
            class="toggle-btn"
          >
            {{ activeQuestionIndex === index ? '收起' : '展开' }}
          </el-button>
        </div>
        <!-- 参考答案 -->
        <div v-if="showAnswers[index]" class="reference-answer">
          <div class="answer-header">
            <i class="el-icon-lightbulb"></i> 参考答案
          </div>
          <div class="answer-content">
            <p>{{ question.answer }}</p>
            <div class="explanation" v-if="question.explanation">
              <p><strong>解析：</strong>{{ question.explanation }}</p>
            </div>
          </div>
          <el-button type="primary" @click="getDetailedAnalysis(index)">获取详细解析</el-button>
        </div>
      </div>
    </div>
    <div v-if="trainingQuestions.length > 0" class="training-actions">
      <el-button @click="resetTraining">
        <i class="el-icon-refresh"></i> 重新生成
      </el-button>
    </div>
  </el-card>
</div>
</template>

<script setup lang="ts">
import { ref, onMounted} from "vue";
import { ElMessage } from "element-plus";
const API_BASE = 'http://localhost:8080';
const API_ENDPOINTS = {
  MODEL: `${API_BASE}/chat`, // 大模型接口
};
import { useInterviewResultStore } from "@/stores/canInterviewResult";
import { useChatWithAIStore } from "@/stores/canChatWithAI";
import { useDrawerVisibleStore } from '@/stores/canDrawerVisible'
import { useButtonVisibleStore } from '@/stores/canButtonVisible'
import { useMessagesStore } from '@/stores/canMessages';

const canInterviewResultStore = useInterviewResultStore();
const canChatWithAIStore = useChatWithAIStore();
const canDrawerVisible = useDrawerVisibleStore();
const canButtonVisible = useButtonVisibleStore();
const canMessages = useMessagesStore();

const knowledgeAssessment = ref(canInterviewResultStore.getMasteryOfKnowledge());

// 训练题相关状态
const isGeneratingTraining = ref(false);
const trainingQuestions = ref<any[]>([
        {
          question: '请简述你对闭包的理解。',
          type: '简答题',
          answer: '闭包是指有权访问另一个函数作用域中变量的函数。',
          difficulty: '中等'
        },
        {
          question: '以下哪个不是 JavaScript 的基本数据类型？',
          type: '选择题',
          options: ['String', 'Number', 'Object', 'Boolean'],
          answer: 'C',
          explanation: 'Object 是引用类型，不是基本数据类型。',
          difficulty: '简单'
        }
      ]
    );
const userAnswers = ref<string[]>([]);
const showAnswers = ref<boolean[]>([]);
const activeQuestionIndex = ref<number>(-1);

onMounted(()=>{ 
  generateTrainingQuestions();
})

// 生成针对性训练题
const generateTrainingQuestions = async () => {
  if (!knowledgeAssessment.value) {
    ElMessage.warning('请先完成面试分析');
    return;
  }
  try {
    isGeneratingTraining.value = true;
    trainingQuestions.value = [];
    ElMessage.info('正在生成针对性训练题...');

    // 构建提示词（改为5道题）
    const prompt = `请根据以下知识薄弱点生成5道针对性训练题：
${knowledgeAssessment.value}
### 题目要求 ###
1. 题目类型：3道选择题（4个选项），2道简答题
2. 每道题包含：
   - 题目内容
   - 题目类型（选择题/简答题）
   - 参考答案（选择题标注正确选项字母）
   - 解析说明（针对选择题）
   - 难度评估（简单/中等/困难）
3. 题目内容需针对候选人的知识短板，具有针对性
4. 格式要求：使用JSON格式返回，包含一个questions数组，每个元素包含以下字段：
   - question: 题目内容
   - type: 题目类型（"选择题"或"简答题"）
   - options: 选择题选项（仅选择题有）
   - answer: 参考答案
   - explanation: 解析说明（仅选择题有）
   - difficulty: 难度级别`;

    const requestData = {
      question: prompt,
      userId: 234,
      deepThinking: true,
      networkSearch: false,
      messages: [
        {
          role: 'system',
          content: '你是一个专业的面试培训师，需要根据知识薄弱点生成针对性训练题'
        },
        {
          role: 'user',
          content: prompt
        }
      ]
    };

    // 使用 fetch 替代 axios 发起流式请求
    const response = await fetch(API_ENDPOINTS.MODEL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'text/event-stream'
      },
      body: JSON.stringify(requestData)
    });

    if (!response.ok || !response.body) {
      throw new Error('流式请求失败');
    }

    // 调用流式解析器处理响应流
    await parseTrainingQuestionsResponse(response.body);

    ElMessage.success('生成训练题成功');
    console.log(trainingQuestions.value)
  } catch (error: any) {
    console.error('生成训练题失败:', error);
    ElMessage.error(`生成失败: ${error.message}`);
  } finally {
    isGeneratingTraining.value = false;
  }
};

// 流式解析函数（保持不变）
const parseTrainingQuestionsResponse = async (responseStream: ReadableStream<Uint8Array>) => {
  try {
    let buffer = '';
    const reader = responseStream.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });

      // 查找 "questions" 字段的起始位置
      const questionsStartIndex = buffer.indexOf('"questions":');
      if (questionsStartIndex === -1) continue;

      // 找到数组的开始位置
      const arrayStartIndex = buffer.indexOf('[', questionsStartIndex);
      if (arrayStartIndex === -1) continue;

      // 查找数组的结束位置
      let depth = 1;
      let arrayEndIndex = arrayStartIndex + 1;
      while (depth > 0 && arrayEndIndex < buffer.length) {
        const char = buffer[arrayEndIndex];
        if (char === '[') depth++;
        if (char === ']') depth--;
        arrayEndIndex++;
      }

      // 如果找到数组的结束
      if (depth === 0) {
        // 截取整个数组的字符串
        const arrayStr = buffer.slice(arrayStartIndex, arrayEndIndex);
        try {
          const questionsArray = JSON.parse(arrayStr);
          if (Array.isArray(questionsArray)) {
            // 过滤有效的问题对象
            const validQuestions = questionsArray.filter(isValidQuestion);
            trainingQuestions.value = validQuestions;
            return { questions: trainingQuestions.value };
          }
        } catch (e) {
          console.error('解析数组失败:', e);
        }
      }
    }

    return { questions: [] };
  } catch (error) {
    console.error('解析训练题失败:', error);
    return {
      questions: [
        {
          question: '请简述你对闭包的理解。',
          type: '简答题',
          answer: '闭包是指有权访问另一个函数作用域中变量的函数。',
          difficulty: '中等'
        },
        {
          question: '以下哪个不是 JavaScript 的基本数据类型？',
          type: '选择题',
          options: ['String', 'Number', 'Object', 'Boolean'],
          answer: 'C',
          explanation: 'Object 是引用类型，不是基本数据类型。',
          difficulty: '简单'
        }
      ]
    };
  }
};

// 验证对象是否符合题目格式
function isValidQuestion(obj: any): boolean {
  if (!obj.question || !obj.type || !obj.answer || !obj.difficulty) {
    return false;
  }

  if (obj.type === '选择题') {
    if (!Array.isArray(obj.options) || !obj.explanation) {
      return false;
    }
    // 可选：验证 options 数组长度是否合理
    if (obj.options.length < 2) return false;
  }

  return true;
}


// 选择选项（选择题）
const selectOption = (index: number, option: string) => {
  userAnswers.value[index] = option;
};

// 显示参考答案
const showAnswer = (index: number) => {
  showAnswers.value[index] = true;
};

// 切换问题展开状态
const toggleQuestion = (index: number) => {
  if (activeQuestionIndex.value === index) {
    activeQuestionIndex.value = -1;
  } else {
    activeQuestionIndex.value = index;
  }
};

// 重置训练题
const resetTraining = () => {
  trainingQuestions.value = [];
  userAnswers.value = [];
  showAnswers.value = [];
  activeQuestionIndex.value = -1;
};

const getDetailedAnalysis = async (index: number) => { 
  canButtonVisible.setButtonVisible(false)
  canDrawerVisible.setDrawerVisible(true)
  canMessages.clearMessages()
  const question = trainingQuestions.value[index];
  const prompt = `请给出${question.question}${question.option ? '，' + question.option : ''}的知识点详细解析。`;
  canChatWithAIStore.setDisplayChatWithAI("请为我生成这道题目的详细解析")
  canChatWithAIStore.setChatWithAI(prompt);
};

</script>

<style scoped>
.training-section {
  width: 100%;
  max-width: 1200px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  margin: 20px auto;
}

.training-card {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e1e8ed;
  background: linear-gradient(to bottom, #ffffff, #f9fbfd);
  transition: all 0.3s ease;
  min-height: 800px;
}

.training-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.training-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #11cb87 0%, #2575fc 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.training-header h3 {
  margin: 0;
  font-size: 20px;
}

.questions-container {
  padding: 20px;
}

.question-item {
  margin-bottom: 25px;
  padding: 20px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #eaeaea;
}

.question-item:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.active-question {
  border-left: 4px solid #3498db;
  background-color: #f8fafc;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.question-number {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.question-content {
  margin-bottom: 20px;
  text-align: left;
}

.question-content p {
  font-size: 16px;
  line-height: 1.6;
  color: #34495e;
}

.options-container {
  margin-top: 15px;
}

.option-item {
  padding: 12px 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: flex-start;
  border: 1px solid #e9ecef;
}

.option-item:hover {
  background-color: #e9f7fe;
  border-color: #d1ecff;
}

.option-item.selected {
  background-color: #d1ecff;
  border-color: #3498db;
  font-weight: 500;
}

.option-letter {
  font-weight: bold;
  margin-right: 10px;
  color: #3498db;
  min-width: 24px;
}

.option-text {
  flex: 1;
  text-align: left;
}

.answer-input {
  margin: 15px 0;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.toggle-btn {
  color: #3498db;
  font-weight: 500;
}

.reference-answer {
  margin-top: 25px;
  padding: 20px;
  background-color: #f0f7ff;
  border-radius: 8px;
  border-left: 3px solid #3498db;
  text-align: left;
}

.answer-header {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.answer-content p {
  font-size: 15px;
  line-height: 1.7;
  color: #2c3e50;
  text-align: left;
}

.explanation {
  margin-top: 15px;
  padding: 12px;
  background-color: #e3f2fd;
  border-radius: 6px;
  font-size: 14px;
  text-align: left;
}

.training-control {
  margin-top: 25px;
  text-align: center;
}

.training-btn {
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 30px;
  background: linear-gradient(135deg, #00b09b, #96c93d);
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 176, 155, 0.3);
}

.training-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 20px rgba(0, 176, 155, 0.4);
}

.training-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.section-title {
  color: #2c3e50;
  border-left: 4px solid #3498db;
  padding-left: 12px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 24px;
}

.header-content {
  max-width: 800px;
  margin: 0 auto;
}

.subtitle {
  font-size: 1.2rem;
  opacity: 0.85;
  max-width: 700px;
  margin: 0 auto 20px;
  line-height: 1.6;
}

h1 {
  font-size: 2.8rem;
  margin-bottom: 15px;
  font-weight: 700;
  letter-spacing: 1px;
}
</style>